<template>
  <el-dialog
    :model-value="dialogDetails"
    width="40%"
    :before-close="handleClose"
  >
    <template #header>
      <h3 style="padding-bottom: 10px">编辑活动模板</h3>
    </template>
    <el-form :model="form" ref="formRef" :rules="rules" label-width="auto">
      <el-form-item label="活动模板名称：" prop="templateName">
        <el-input
          v-model="form.templateName"
          placeholder="请输入活动模板名称"
          clearable
          v-noSpace
        />
      </el-form-item>
      <el-form-item label="活动类型：" prop="typeId">
        <el-select
          v-model="form.typeId"
          placeholder="请选择活动类型"
          clearable
          @focus="getClick"
          :loading="loading"
        >
          <el-option
            v-for="item in ParentList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="内容：" prop="templateInfo">
        <WangEditor
          v-model="form.templateInfo"
          height="200"
          @change="handleEditorChange"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import WangEditor from '@/components/WangEditor/index.vue';
import { addActivityLibrary } from '@/api/Activity/library';
import { getActivityCategorySelect } from '@/api/Activity/category';

// 添加用户数据
const form = ref({
  templateName: '',
  typeId: '',
  templateInfo: '',
});
const ParentList = ref([]);
const loading = ref(false);

// 校验规则
const formRef = ref(null);
const rules = {
  templateName: [
    { required: true, message: '请输入活动模板名称', trigger: 'blur' },
  ],
  typeId: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
  templateInfo: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || value.trim() === '<p><br></p>') {
          callback(new Error('请输入内容'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

// 定义 props，接收父组件传递的数据
const props = defineProps({
  dialogDetails: {
    type: Boolean,
  },
  DetailsRow: {
    type: Object,
  },
});

// 监听弹窗显示和数据变化
watch(
  () => props.dialogDetails,
  (newVal) => {
    if (newVal && props.DetailsRow) {
      // 当弹窗打开且有数据时，初始化表单
      initFormData();
    }
  }
);

// 初始化表单数据
const initFormData = async () => {
  const row = props.DetailsRow;
  if (row.templateName) {
    loading.value = true;
    try {
      const res = await getActivityCategorySelect({});
      if (res.data.code === 200) {
        ParentList.value = res.data.data;
        form.value = {
          templateName: row.templateName || '',
          typeId: '', // 先设置为空
          templateInfo: row.templateInfo || '',
        };
        // 在列表加载完成后，再设置typeId
        if (row.typeId) {
          const currentType = ParentList.value.find(
            (item) => String(item.id) === String(row.typeId)
          );
          if (currentType) {
            form.value.typeId = currentType.id;
          }
        }
      }
    } catch (error) {
      console.error('获取活动类型列表失败:', error);
    } finally {
      loading.value = false;
    }
  } else {
    form.value = {
      templateName: '',
      typeId: '',
      templateInfo: row.templateInfo || '',
    };
  }
};

// 定义 emits，向父组件发送事件
const emit = defineEmits(['confirm', 'cancel']);

// 处理取消按钮的点击事件
const handleCancel = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {};
  ParentList.value = [];
  emit('cancel');
};

// 处理确认按钮的点击事件
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await addActivityLibrary({
        id: props.DetailsRow.id,
        ...form.value,
      });
      if (res.data.code === 200) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: '修改成功',
          type: 'success',
        });
        emit('confirm');
        handleClose();
      } else {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'error',
        });
      }
    }
  });
};
const getClick = () => {
  ActivityLibraryList();
};
// 获取活动分类下拉
const ActivityLibraryList = async () => {
  loading.value = true;
  try {
    const res = await getActivityCategorySelect({});
    if (res.data.code === 200) {
      ParentList.value = res.data.data;
      // 如果当前有选中的typeId，需要重新匹配
      if (form.value.typeId) {
        const currentType = ParentList.value.find(
          (item) => String(item.id) === String(form.value.typeId)
        );
        if (!currentType) {
          form.value.typeId = ''; // 如果找不到匹配项，清空选择
        }
      }
    } else {
      // eslint-disable-next-line no-undef
      ElMessage({
        message: res.data.msg,
        type: 'error',
      });
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 处理编辑器内容变化
const handleEditorChange = (html) => {
  form.value.templateInfo = html;
  // 手动触发表单验证
  formRef.value?.validateField('templateInfo');
};

// 关闭对话框
const handleClose = () => {
  handleCancel();
};

onMounted(() => {});
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
